<template>
<div class="main-login">
  <el-form :model="ruleForm" :rules="rules2" ref="ruleForm" label-position="left" label-width="0px" class="demo-ruleForm login-container">
    <h3 class="title">软件部考核系统</h3>
    <el-form-item prop="account">
      <el-input type="text" v-model="ruleForm.account" auto-complete="off" @change='change' placeholder="账号"></el-input>
    </el-form-item>
    <el-form-item prop="checkPass">
      <el-input type="password" v-model="ruleForm.checkPass" auto-complete="off" @change='change' placeholder="密码" @keyup.enter.native="handleSubmit"></el-input>
    </el-form-item>
    <el-checkbox v-model="checked" @change='change' class="remember">记住密码</el-checkbox>
    <el-button round style="float:right;" @click="forget">忘记密码</el-button>
    <el-form-item style="width:100%;">
      <el-button  type="primary" style="width:100%;" @click.native.prevent="handleSubmit" :loading="logining">登录</el-button>
    </el-form-item>
    <div v-if="sys_error" class="err-msg">{{sys_error}}</div>
  </el-form>
</div>
</template>

<script>
  import { mapState, mapMutations, mapActions } from 'vuex'
  import util from '@/util/util' 

  export default {
    data() {
      return {
        logining: false,
        ruleForm: {
          account: '',
          checkPass: ''
        },
        rules2: {
          account: [
            { required: true, message: '请输入账号', trigger: 'blur' }
          ],
          checkPass: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
        },
        sys_error: '',
        checked: false,

        //菜单
        navlist: [
          {
              path: '/home',
              name: '首页',
              icon: 'el-icon-star-on',
              active: true
          },
          {
              name: '加班管理',
              icon: 'el-icon-tickets',
              active: true,
              child: [{
                      name: '加班管理',
                      icon: 'el-icon-star-off',
                      path: '/overtime/manage',
                      active: true,
                      permission: ['查询','编辑','导入','提交']
                  },
                  {
                      name: '加班汇总',
                      icon: 'el-icon-search',
                      path: '/overtime/summary',
                      active: true,
                      permission: ['查询','明细']
                  }
              ]
          },
          {
              name: '考核管理',
              icon: 'el-icon-tickets',
              active: true,
              child: [{
                      name: '考核管理',
                      icon: 'el-icon-star-off',
                      path: '/assess/manage',
                      active: true
                  },
                  {
                      name: '考核汇总',
                      icon: 'el-icon-search',
                      path: '/assess/summary',
                      active: true
                  }
              ]
          },
          {
            name: '用户管理',
            path: '/baseInfo/system/user',
            icon: 'el-icon-bell',
            active: true,
            permission: ['编辑', '删除', "新增", "查询", "注销", "重置密码", "导出"]
          },
          {
            name: '部门管理',
            path: '/baseInfo/branch',
            icon: 'el-icon-goods',
            active: true,
            permission: ['编辑', '删除', "新增", "查询"]
          },
          {
            name: '角色管理',
            path: '/baseInfo/post',
            icon: 'el-icon-service',
            active: true,
            permission: ['编辑',  "新增", "查询", "配置权限", "删除"]
          },
          {
            name: '修改密码',
            path: '/baseInfo/system/password',
            icon: 'el-icon-warning',
            active: true
          }
        ]
      };
    },
    computed: {
        
    },
    methods: {
      ...mapActions({
          requestLogin: 'user/requestLogin'
      }),
      ...mapActions({
          getPermission: 'permission/getPermission'
      }),
      change(){
        if(this.checked){
          localStorage.setItem('userForm', JSON.stringify(this.ruleForm));
        }else{
          localStorage.removeItem('userForm');
        }
      },
      forget(){
        this.$notify.info({
          title: '提示',
          duration: 1000,
          message: '请联系管理员重置密码'
        });
      },
      handleSubmit() {
        //处理后台返回的权限菜单数据方法
        // function dealWithData(json){
        //   for(var i = 0; i<json.length; i++){
        //     if((json[i].active === false)){
        //       json = json.splice(i,1);
        //     }
        //     if('child' in json[i]){
        //       delete json[i]['baseRoles']
        //       delete json[i]['meta']
        //       json[i] = JSON.parse(JSON.stringify(json[i]).replace(/iconCls/g,"icon"))
        //       dealWithData(json[i].child)
        //     }
        //   }
        //   return json;
        // };
        
        // 后台菜单数据结构处理
        function dealWithData(json){
          for(var i = 0; i<json.length; i++){
            if('child' in json[i]){
              delete json[i]['baseRoles']
              delete json[i]['meta']
              delete json[i]['requireAuth']
              if(json[i].child.length>0){
                if(json[i].child[0].active == false){
                  json[i]['permission'] = []
                  for(var j = 0; j<json[i].child.length; j++){
                    json[i]['permission'].push(json[i].child[j].name)
                  }
                  json[i]['child'] = []
                }
              }
              dealWithData(json[i].child)
            }
          }
          return json;
        };

        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.logining = true;
            let url = 'login?username='+this.ruleForm.account+ '&password='+ this.ruleForm.checkPass;
            
            this.$http.post(url)
            .then(
                (response) => {
                    if (response.data.status === 200) {
                      let data = response.data;
                      this.logining = false;
                      let baseRoles = data.data.baseRoles;
                      let roleId = baseRoles[0].id;
                      // 重置浏览器存储
                      localStorage.removeItem("menu")
                      localStorage.removeItem("role")
                      localStorage.removeItem("user")
                      
                      this.requestLogin(data.data).then(res => {
                          localStorage.setItem('user', JSON.stringify(res));
                      }).catch(err => {
                          
                      })
                      
                      // 获取菜单
                      // 替换属性
                      // let menuList = dealWithData(JSON.parse(JSON.stringify(data.data.baseMenus).replace(/children/g,"child").replace(/keepAlive/g,"active").replace(/iconCls/g,"icon")));
                      // menuList.unshift({
                      //     path: '/home',
                      //     name: '首页',
                      //     icon: 'el-icon-star-on',
                      //     active: true
                      // });
                      // this.navlist = menuList;

                      localStorage.setItem('menu', JSON.stringify(this.navlist));
                      this.$router.replace('home')
                    } else {
                        this.logining = false;
                        this.$message({
                            message: response.data.data,
                            type: 'warning'
                        });
                    }
                },
                (error) => {
                  this.logining = false;
                  this.$message({
                      message: '服务端异常，请联系技术支持',
                      type: 'error'
                  });
                }
            );
          } else {
            console.log('error submit!!');
            return false;
          }
        });

        setTimeout(()=>{
          this.logining = false;
        },3000)
      },
      // 记住密码 set
      setUser(){
        if(localStorage.getItem('userForm')){
          let user = JSON.parse(localStorage.getItem('userForm'));
          this.ruleForm.account = user.account;
          this.ruleForm.checkPass = user.checkPass;
          this.checked = true;
        }
      }
    },
    mounted() {
      this.setUser()
      localStorage.setItem('menu', '');
    }
  }

</script>

<style lang="scss" scoped>
  .main-login{
    margin: 0 auto;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: #2d3a4b;
    // background: #18c8f6;
    // 改
    // height: 100%;
    // background:url("~sysStatic/images/login.jpg") no-repeat center fixed;
    // -webkit-background-size: cover;
    // -moz-background-size: cover;
    // -o-background-size: cover;
    // background-size: cover;
    // color: rgba(255,255,255,.5);
  }
  .login-container {
    box-shadow: 0 0px 8px 0 rgba(0, 0, 0, 0.06), 0 1px 0px 0 rgba(0, 0, 0, 0.02);
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    margin: 150px auto;
    width: 450px;
    padding: 35px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    .title {
      margin: 0px auto 40px auto;
      text-align: center;
      color: #505458;
    }
    .remember {
      margin: 10px 0px 35px 0px;
    }
  }
</style>